﻿using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.ExceptionManagement;
using Kiiro.Validation.Validators.Entities;

namespace Kiiro.Model.EventHandlers.ItemEventHandlers
{
    public class DocumentItemEventReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            if ( properties.ListItem != null && properties.ListItem.File != null )
            {
                Document document = SPDataHelpers.MakeDocumentFromFileItem ( properties.ListItem );

                try
                {
                    ActivityHistory activity = PopulateDocumentHistory ( document );
                    activity.ActivityReferenceUrl = properties.ListItem.ID.ToString ( );
                    if ( activity.CreatedBy.Id == 0 && activity.CreatedBy.Login != null )
                    {
                        activity.CreatedBy = UserModel.GetUserByLogin ( activity.CreatedBy.Login, properties.SiteId, properties.RelativeWebUrl );
                        activity.ModifiedBy = activity.CreatedBy;
                    }
                    activity.EventType = EventType.Created;

                    ActivityHistoryModel.Save ( activity, properties.SiteId, properties.RelativeWebUrl );
                }
                finally
                {
                    document.IsCreatedThisWeekAdd = true;
                    Midori midori = new Midori { Documents = new List<Document> { document } };
                    ProjectsModel.UpdateProjectStatistics ( midori, properties.SiteId, properties.RelativeWebUrl );
                }
            }

            base.ItemAdded(properties);
        }

        public override void ItemDeleting(SPItemEventProperties properties)
        {
            if ( properties.ListItem != null && properties.ListItem.File != null )
            {
                Document document = SPDataHelpers.MakeDocumentFromFileItem ( properties.ListItem );
                document.EditType = EditType.Deleted;
                Midori midori = new Midori { Documents = new List<Document> { document } };
                ProjectsModel.UpdateProjectStatistics ( midori, properties.SiteId, properties.RelativeWebUrl );
            }

            base.ItemDeleting(properties);
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            if ( properties.ListItem != null && properties.ListItem.File != null )
            {
                if ( properties.ListItem.Versions.Count > 1 && properties.ListItem [ "Document.CurrentVersion" ] != null &&
                    properties.ListItem.Versions.Count != ( int ) properties.ListItem [ "Document.CurrentVersion" ] )
                {
                    Document document = SPDataHelpers.MakeDocumentFromFileItem ( properties.ListItem );

                    try
                    {
                        if ( !document.IsProjectPlan )
                        {
                            ActivityHistory activity = PopulateDocumentHistory ( document );
                            activity.ActivityReferenceUrl = properties.ListItem.ID.ToString ( );

                            activity.EventType = EventType.Versioned;
                            if ( activity.CreatedBy.Id == 0 && activity.CreatedBy.Login != null )
                            {
                                activity.CreatedBy = UserModel.GetUserByLogin ( activity.CreatedBy.Login, properties.SiteId, properties.RelativeWebUrl );
                                activity.ModifiedBy = activity.CreatedBy;
                            }

                            ActivityHistoryModel.Save ( activity, properties.SiteId, properties.RelativeWebUrl );
                        }
                    }
                    finally
                    {
                        int dayOfWeekNum = ( int ) DateTime.Now.DayOfWeek;
                        DateTime firstOfWeek = DateTime.Today.AddDays ( -dayOfWeekNum );

                        int versionsRequired = document.CreatedDate >= firstOfWeek ? 2 : 1;
                        if ( properties.ListItem.Versions.Cast<SPListItemVersion> ( ).Count ( x => x.Created >= firstOfWeek ) == versionsRequired )
                        {
                            document.IsUpdatedThisWeekAdd = true;
                            Midori midori = new Midori { Documents = new List<Document> { document } };
                            ProjectsModel.UpdateProjectStatistics ( midori, properties.SiteId, properties.RelativeWebUrl );
                        }
                    }
                }
            }

            base.ItemUpdated(properties);
        }

        /// <summary>
        /// Updates the project statistics if the document has been updated
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
        }

        private ActivityHistory PopulateDocumentHistory(Document document)
        {
            ActivityHistory activity = new ActivityHistory();           

            activity.CreatedBy = document.ModifiedBy;
            activity.CreatedDate = document.ModifiedDate;
            activity.ModifiedBy = document.ModifiedBy;
            activity.ModifiedDate = document.ModifiedDate;
            activity.Title = document.Title;

            activity.ActivityItemType = ItemType.Document;            

            activity.EditType = EditType.Created;

            return activity;
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.Model/EventHandlers/ItemEventHandlers/DocumentItemEventReceiver.cs $
 * 
 * 7     10/11/09 1:09p Camerons
 * 
 * 6     9/11/09 9:00p Camerons
 * 
 * 5     8/11/09 3:00p Camerons
 * 
 * 4     30/09/09 9:23a Shafia
 * 
 * 3     17/08/09 10:29a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/